/**
 *
 * 2007-11-2 上午10:39:30
 * @author xuhuan
 */

package edu.ccut.saturn.studio.logic.model.xml;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

import edu.ccut.saturn.studio.core.util.xml.SaturnW3CUtil;
import edu.ccut.saturn.studio.logic.model.Shape;
import edu.ccut.saturn.studio.logic.model.ShapesDiagram;
import edu.ccut.saturn.studio.logic.model.xml.loader.ConnectionLoader;
import edu.ccut.saturn.studio.logic.model.xml.loader.NodeLoader;

public abstract class ModelXmlUtils {

	public static List<Shape> loadModels(Document document, NodeLoader[] loaders) {
		List<Shape> shapes = new ArrayList<Shape>();
		Element root = document.getDocumentElement();

		for (NodeLoader loader : loaders) {
			shapes.addAll(loader.loadNodes(root));
		}

		new ConnectionLoader().loadNodeForConnection(root, shapes);
		return shapes;
	}

	public static void refreshModelXml(ShapesDiagram diagram) {
		List<Shape> shapes = diagram.getShapes();

		Set<Shape> modifyShapes = diagram.getModifyShapes();

		for (Shape shape : modifyShapes) {
			shape.refresh();
		}

		if (shapes != null && !shapes.isEmpty()) {
			Node root = shapes.get(0).getRoot();

			for (Shape shape : shapes) {
				shape.createConnections();
			}
			
			SaturnW3CUtil.format(root);
		}
		diagram.removeModifyShapes();
	}

}
